<template>
  <div class="hq-search-condition">
    <el-form
      ref="searchCondition"
      class="hq-search-condition_form"
      v-bind="props.formAttrs"
      :inline="true"
      :model="props.models"
      :rules="props.formRules"
    >
      <el-form-item
        v-for="field in props.fields"
        :key="field.prop"
        :prop="field.prop"
        :label="field.label"
        v-bind="field.attrs"
        :class="{ 'date-from-item': field?.attrs?.type === 'datetimerange' }"
      >
        <component
          :is="components[field.type]"
          :models="props.models"
          :field="field"
        ></component>
      </el-form-item>
    </el-form>
    <div class="hq-search-condition_action">
      <el-button type="primary" size="small" @click="onSubmit">
        查询
      </el-button>
      <el-button type="info" size="small" @click="resetFields">
        重置
      </el-button>
      <slot name="actionBtn"></slot>
    </div>
  </div>
</template>

<script setup lang="ts">
import components from './index'
import { submitForm, resetForm } from '@/utils'
import { ref, toRaw } from 'vue'
import { FormInstance, FormRules } from 'element-plus'
import { IBaseFieldItem } from './interface'

interface IProps {
  fields: IBaseFieldItem[] // 表单数据
  models: Record<string, string | number> // 表单数据对象 v-model
  formAttrs?: Record<string, string | number | boolean> // 表单属性
  formRules?: FormRules // 校验规则
}
const props = withDefaults(defineProps<IProps>(), {
  formAttrs: () => ({}),
  formRules: () => ({})
})

const emit = defineEmits(['success', 'error', 'rest'])

const searchCondition = ref<FormInstance | null>(null)
/**
 * 重置
 */
function resetFields() {
  resetForm(searchCondition.value!)
  emit('rest')
}

/**
 * 提交
 */
async function onSubmit() {
  const pass = await submitForm(searchCondition.value!)
  if (pass) {
    const temp = toRaw(props.models)
    emit('success', temp)
  } else {
    emit('error')
  }
}
</script>

<style scoped lang="scss">
.hq-search-condition {
  width: 100%;
  display: flex;
  flex-direction: column;
  &_form {
    :deep().el-form--inline {
      display: inline-block;
      width: 100%;
    }
    :deep().el-form-item {
      height: 40px;
      align-items: center;
      box-sizing: border-box;
      float: left;
      margin-bottom: 5px;
    }
    :deep().el-form-item__label {
      width: 120px !important;
      align-items: center;
    }
    .el-input,
    .el-select,
    .el-input-number,
    :deep().el-date-editor.el-input {
      width: 200px !important;
    }
  }
  &_action {
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }
}
</style>
